<template>
	<div>
		<div v-for="(period, index) in periodArr" :key="index">
			<el-time-picker
				v-model="periodArr[index]"
				format="HH:mm"
				is-range
				range-separator="到"
				start-placeholder="开始时间"
				end-placeholder="结束时间"
				:clearable="false"
			/>
			<el-button type="success" style="margin-left: 20px" @click="handleAddPeriod">+</el-button>
			<el-button type="danger" @click="handleRemovePeriod(index)">×</el-button>
		</div>
		<div style="margin-top: 20px">
			<el-button type="primary" @click="handleConfirm">确 定</el-button>
			<el-button @click="$emit('handleClosePeriodDialog')">取 消</el-button>
		</div>
	</div>
</template>

<script lang="ts">
import { queryPeriodByAlarmId, updatePeriodByAlarmId } from '@/api/middle-platform/conf-alarm';
import { parseTime } from '@/utils/common';

export default {
	name: 'ConfAlarmPeriod',
	props: {
		currentAlarmId: {
			type: Number,
			default: 0,
		},
	},
	emits: ['handleClosePeriodDialog'],
	data() {
		return {
			periodArr: [],
		};
	},
	watch: {
		currentAlarmId: {
			handler(newVal, oldVal) {
				queryPeriodByAlarmId(newVal).then((res: object) => {
					this.periodArr = [];
					const arr = res.data;
					arr.forEach((period: object) => {
						this.periodArr.push([new Date('2023-05-20 ' + period.alarmStartTime + ':00'), new Date('2023-05-20 ' + period.alarmEndTime + ':00')]);
					});
				});
			},
			immediate: true,
		},
	},
	methods: {
		handleAddPeriod() {
			if (this.periodArr.length < 10) {
				this.periodArr.push([new Date('2023-05-20 00:00:00'), new Date('2023-05-20 00:00:00')]);
			}
		},
		handleRemovePeriod(index: number) {
			if (this.periodArr.length > 1) {
				this.periodArr.splice(index, 1);
			}
		},
		handleConfirm() {
			const arr = [];
			this.periodArr.forEach((period: any) => {
				arr.push({
					alarmStartTime: parseTime(period[0], '{h}:{i}'),
					alarmEndTime: parseTime(period[1], '{h}:{i}'),
				});
			});
			updatePeriodByAlarmId({ id: this.currentAlarmId, periodList: arr }).then((res: object) => {
				this.$message.success('修改成功');
				this.$emit('handleClosePeriodDialog');
			});
		},
	},
};
</script>

<style scoped></style>
